<?php

namespace app\common\model\user;

use app\common\model\User;
use think\Model;
use traits\model\SoftDelete;

class Artwork extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'user_artwork';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [

    ];

    protected $hidden = [
        'deletetime'
    ];


    const STATUS_SNAPSHOT = 0;//快照(快照状态不可编辑)
    const STATUS_NORMAL = 1;//正常

    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public static function updateVersion($id)
    {
        return self::where(['id' => $id])
            ->inc('version', 1)
            ->update();
    }



    // 生成快照, 已经存在相同版本的快照信息则返回
    public static function genSnapshot($id, $version)
    {
        $snapshot = self::where(['pid' => $id, 'version' => $version, 'status' => self::STATUS_SNAPSHOT])->find();
        if (!empty($snapshot)) {
            return $snapshot;
        }

        $res = self::where(['id' => $id, 'version' => $version])->find();
        if (empty($res)) {
            return false;
        }

        $origin = $res->toArray();
        $data = $origin;
        $data['status'] = self::STATUS_SNAPSHOT;
        $data['pid'] = $origin['id'];
        $data['id'] = 0;

        $model = new self;
        $result = $model->save($data);
        if (empty($result)) {
            return false;
        }

        $artworkAttributeRes = ArtworkAttribute::where(['artwork_id' => $id])->select();
        if (empty($artworkAttributeRes)) {
            return false;
        }
        $batchData = [];
        foreach ($artworkAttributeRes as $artworkAttribute) {
            $origin = $artworkAttribute->toArray();
            $data = $origin;
            $data['id'] = 0;
            $data['artwork_id'] = $model->id;
            $batchData[] = $data;
        }
        $result = $model->artworkAttribute()->saveAll($batchData);
        if (empty($result)) {
            return false;
        }
        return $model;
    }




    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function artworkAttribute()
    {
        return $this->hasMany(ArtworkAttribute::class, 'artwork_id', 'id');
    }
}
